package com.ayokunlepaul.frescoloader;

import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.imagepipeline.image.CloseableBitmap;
import com.veinhorn.scrollgalleryview.loader.MediaLoader;
import com.veinhorn.scrollgalleryview.util.LogUtil;
import ohos.agp.components.Image;
import ohos.media.image.PixelMap;

/**
 * DataSubscriberAchieve
 *
 * @since 2021-05-21
 */
public class DataSubscriberAchieve extends BaseDataSubscriber<CloseableReference<CloseableBitmap>> {
    private Image mImageView;
    private MediaLoader.SuccessCallback mCallback;

    /**
     * DataSubscriberAchieve
     *
     * @param imageView
     * @param callback
     */
    public DataSubscriberAchieve(Image imageView, MediaLoader.SuccessCallback callback) {
        this.mImageView = imageView;
        this.mCallback = callback;
    }

    /**
     * onNewResultImpl
     *
     * @param dataSource
     */
    @Override
    protected void onNewResultImpl(DataSource<CloseableReference<CloseableBitmap>> dataSource) {
        if (!dataSource.isFinished()) {
            return;
        }
        CloseableReference<CloseableBitmap> result = dataSource.getResult();
        if (result != null) {
            final CloseableReference<CloseableBitmap> resultCopy = result.clone();
            try {
                CloseableBitmap closeableBitmap = resultCopy.get();
                PixelMap bitmap = closeableBitmap.getUnderlyingBitmap();
                if (bitmap != null && !bitmap.isReleased()) {
                    mImageView.setPixelMap(bitmap);
                    mCallback.onSuccess();
                }
            } finally {
                result.close();
                resultCopy.close();
            }
        }
    }

    /**
     * onFailureImpl
     *
     * @param dataSource
     */
    @Override
    protected void onFailureImpl(DataSource<CloseableReference<CloseableBitmap>> dataSource) {
        Throwable cause = dataSource.getFailureCause();
        if (cause != null) {
            LogUtil.error("onFailureImpl", cause.getMessage());
        }
    }
}
